<?php
namespace control;
/*
*招聘需求类
*/

class recruitmentClass extends adIndexClass
{
    private const page = 'recruitment';
    private const table = 'recruitment';
    private const title = '招聘需求';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            text(array("name" => "orderNo", "title" => L('recruitment.table.orderNo'))) .
            text(array("name" => "jobName", "title" => L('recruitment.table.jobName'))) .
            text(array("name" => "deptName", "title" => L('recruitment.table.deptName'))) .
            selectMultiple(array("name" => "stid", "title" => L('recruitment.table.stid'), "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid')) .
            text(array("name" => "createTime",'class'=>'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('recruitment.table.createTime')."-".L('recruitment.table.createTime'))) .
            select(array("name" => "state", "title" => L('recruitment.table.state'), "option" => $this->stateOption));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "jobName" => $this->post('jobName'),//职位名称
            "orderNo" => $this->post('orderNo'),//单据编号
            "deptName" => $this->post('deptName'),//申请人部门
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "stid" => $this->post('stid'),//申请人
        );
        $and = $this->seeSelf(self::page);
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        //排序
        $orderBy = $this->orderBy(array(
            "search" => $this->post('orderBy') ?? null,
            "default" => "创建日期降序",
            "array" => array(
                "time" => array("desc" => "创建日期降序"),
            ),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = [$checkAll, L('recruitment.table.orderNo'), L('recruitment.table.jobName'),  L('recruitment.table.needPeople'), L('recruitment.table.expectTime'), L('recruitment.table.deptName'), L('recruitment.table.stid'), L('recruitment.table.state'),L('recruitment.table.dutyText'), L('recruitment.table.createTime')];
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => $array['state'] == '草稿' ? array("title" => L('recruitment.table.edit'), "click" => "newIframe('" . L('recruitment.table.recruitmentInfo') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')") : [],
                "detail" => array("title" => L('recruitment.table.recruitmentInfo'), "click" => "newIframe('".L('recruitment.table.recruitmentInfo')."','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $tr[] = [ $this->dominate($dominate), $array['orderNo'], $array['jobName'], $array['num'], $array['arrivalDate'], $array['deptName'], self::findStaff($array['stid']),$array['state'], zishu($array['jobText'], 30), $array['time'] ];
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('".L('recruitment.table.recruitmentInfo')."','" . $url . "&fun=edit')\" class='spanButton'>".L('recruitment.table.add')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('recruitment.table.del')."</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

	

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $job = query('job', "id = '$info[jobId]'");
        //现编人数
        $people = static::total(array('table' => 'staff', 'where' => "jobId = '$info[jobId]' and state !='离职' and workFlow ='已复核'"));
        $formalStaff = static::total(array('table' => 'staff', 'where' => "jobId = '$info[jobId]' and state in ('转正','留职') and workFlow = '已复核'"));
        $practiceStaff = static::total(array('table' => 'staff', 'where' => "jobId = '$info[jobId]' and state ='试用' and workFlow = '已复核'"));
        $job['people'] = $job['people'] ?: '-';
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    must . L('recruitment.table.jobName')."：" => selectMultiple([
                        "name" => "jobId", "title" => L('recruitment.table.choose'),
                        'value' => $info['jobId'],
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'table' => "job",
                        'where' => "1=1 order by list",
                        'change' => "getJobInfo"
                    ]),
                ],
                [
                    L('recruitment.table.preparation')."：" => L('recruitment.table.finalization')."<span id='limitPeople'>{$job['people']}</span>，".L('recruitment.table.impromptu')."<span id='jobPeople'>{$people}</span>（".L('recruitment.table.formal')."<span id='formalStaff'>$formalStaff</span>，".L('recruitment.table.internship')."<span id='practiceStaff'>$practiceStaff</span>）"
                ],
                [
                    must . L('recruitment.table.needPeople')."：" => text(["name" => "num", 'type' => 'number', 'class' => 'text textPrice', "value" => $info['num']]),
                ],
                [
                    must . L('recruitment.table.expectTime')."：" => text(["name" => "arrivalDate", 'class' => 'select', 'laydate' => [], "value" => $info['arrivalDate']]),
                ],
                [
                    must . L('recruitment.table.dutyText')."：" => textarea(["name" => "jobText", "value" => $info['jobText']])
                ],
                [
                    must . L('recruitment.table.requirements')."：" => textarea(["name" => "workText", "value" => $info['workText']])
                        . hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
                ],
            ],
            'button' => '<button class="button left-bottom" onclick="subForm(\'recruitmentEditForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=editEdit\')">提交</button>',
        ]);
        $data['html'] .= <<<eof
<script>
function getJobInfo(e){
    $.post(root+'control/adIndex.html?cla=recruitment&fun=getJobInfo',{id:e.value},function(res) {
        $("#limitPeople").html(res.data.limitPeople);
        $("#jobPeople").html(res.data.jobPeople);
        $("#formalStaff").html(res.data.formalStaff);
        $("#practiceStaff").html(res.data.practiceStaff);
        $("[name='jobText']").html(res.data.text);
        $("[name='workText']").html(res.data.requirement);
    },'json')
}
</script>
eof;

        //返回
        return $this->tab($data);
    }


    public function getJobInfo()
    {
        $jobId = $this->post('id');
        //现编人数
        $job = query('job', "id = '$jobId'");
        $people = static::total(array('table' => 'staff', 'where' => "jobId = '$jobId' and state !='离职' and workFlow = '已复核'"));
        $formalStaff = static::total(array('table' => 'staff', 'where' => "jobId = '$jobId' and state in ('转正','留职') and workFlow = '已复核'"));
        $practiceStaff = static::total(array('table' => 'staff', 'where' => "jobId = '$jobId' and state ='试用' and workFlow = '已复核'"));
        $json['data'] = [
            'limitPeople' => $job['people'],
            'formalStaff' => $formalStaff,
            'practiceStaff' => $practiceStaff,
            'jobPeople' => $people,
            'requirement'=>$job['requirement'],
            'text'=>$job['text']
        ];
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'jobId' => $this->post('jobId'),
            'num' => $this->post('num'),
            'arrivalDate' => $this->post('arrivalDate'),
            'jobText' => $this->post('jobText'),
            'workText' => $this->post('workText'),
        ];
        $annotation = [
            'jobId' => L('recruitment.table.jobName'),
            'num' => L('recruitment.table.needPeople'),
            'arrivalDate' => L('recruitment.table.expectTime'),
            'jobText' => L('recruitment.table.dutyText'),
            'workText' => L('recruitment.table.requirements'),
        ];
        $rules = [
            'jobId' => 'required',
            'num' => 'required|unsigned_int',
            'arrivalDate' => 'required',
            'jobText' => 'required',
            'workText' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('recruitment.table.edit_permission');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            $job = query('job', " id = '$field[jobId]'");
            $department = query('department', " id = '{$this->controlJob['departmentId']}'");
            $field['jobName'] = $job['name'];
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'ZPXQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'deptName' => $department['name'],
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
                $userNo = $info['orderNo'];
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{id}}','{{orderNo}}'],[$this->control['name'],$id,$userNo],L('recruitment.table.editLog'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];

        if (($info['state'] == '草稿' && $this->power(self::page, "edit")) || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => L('recruitment.table.commitAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '招聘需求',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],

                ], 320))],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => L('recruitment.table.addAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                ], 320))],
            ];
            $button[] = [
                "name" => L('recruitment.table.transmit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                ], 320))],
            ];
            $button[] = [
                "name" =>L('recruitment.table.audit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('recruitment.table.cancel'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }


    /*详情页*/
    public function detail(): string
    {
        $recruitment = query(self::table, " id = '{$this->get('id')}'");
        if (empty($recruitment['id'])) {
            $html = L('recruitment.table.no_info');
        } else {
            //菜单
            $data = array(
                "id" => $recruitment['id'],
            );
            $button = [];
            if ($this->power(self::page, "edit") && $recruitment['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.edit'),
                    "type" => "顶部页卡",
                    "title" => L('recruitment.table.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $recruitment['id'],
                ];
            }
            if ($this->power(self::page, "del") && $recruitment['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" =>L('recruitment.table.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $recruitment['id']],
                ];
            }

            //审核按钮
            $button = array_merge($button, $this->auditButton($recruitment));
            $audit = query('audit', " targetId = '$recruitment[id]'");
            //现编人数
            $job = query('job', "id = '$recruitment[jobId]'");
            $people = static::total(array('table' => 'staff', 'where' => "jobId = '$recruitment[jobId]' and state !='离职' and workFlow = '已复核'"));
            $formalStaff = static::total(array('table' => 'staff', 'where' => "jobId = '$recruitment[jobId]' and state in ('转正','留职') and workFlow = '已复核'"));
            $practiceStaff = static::total(array('table' => 'staff', 'where' => "jobId = '$recruitment[jobId]' and state ='试用' and workFlow = '已复核'"));
            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                array(
                    array(
                        L('recruitment.table.jobName') => $recruitment['jobName'],
                        L('recruitment.table.needPeople') => $recruitment['num'],
                        L('recruitment.table.expectTime') => $recruitment['arrivalDate'],
                    ),
                    array(
                        L('recruitment.table.expectTime') => L('recruitment.table.finalization')."<span id='limitPeople'>{$job['people']}</span>，".L('recruitment.table.impromptu')."<span id='jobPeople'>{$people}</span>（".L('recruitment.table.formal')."<span id='formalStaff'>$formalStaff</span>，".L('recruitment.table.internship')."<span id='practiceStaff'>$practiceStaff</span>）"
                    ),
                    array(
                        L('recruitment.table.preparation') => neirong(html_entity_decode($recruitment['jobText'], ENT_QUOTES)),
                    ),
                    array(
                        L('recruitment.table.requirements') => neirong(html_entity_decode($recruitment['workText'], ENT_QUOTES)),
                    ),
                ),
                L('recruitment.table.system_info') => array(
                    array(
                        L('recruitment.table.orderNo') => $recruitment['orderNo'],
                        L('recruitment.table.deptName') => $recruitment['deptName'],
                        L('recruitment.table.stid') => self::findStaff($recruitment['stid']),
                    ),
                    array(
                        L('recruitment.table.createTime') => $recruitment['time'],
                        L('recruitment.table.commitTime') => self::null($audit['commitTime']),
                        L('recruitment.table.state') => $recruitment['state'],
                    ),
                ),
                L('recruitment.table.flow') => array(
                    array(
                        auditClass::auditRecord(self::table, $recruitment['id'])
                    )
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('recruitment.table.del_re');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'],[$msg],L('recruitment.table.msg'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /*批量删除*/
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('recruitment.table.del_per');
        } elseif (empty($array)) {
            $json['warn'] = L('recruitment.table.no_data');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = L('recruitment.table.draft');
                } else {
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('recruitment.table.del_suc');
                    $x++;
                }

                $text .= str_replace(['{{id}}','{{jobName}}'],[$info['id'],$info['jobName']],L('recruitment.table.del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('recruitment.table.del_res'))."<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('recruitment.table.del_log'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


}

